<template>
  <div class="service-page">
    <div class="content">
      <div class="search-bar-box">
        <span>插件名称：</span>
        <a-input
          v-model="searchPluginName"
          class="pluginKeyName"
          placeholder="请输入插件名搜索..."
        />
        <span>状态:</span>
        <a-select
          v-model="searchPluginStatus"
          class="comp-select"
          default-value=""
        >
          <a-select-option
            v-for="option in filterStatusList"
            :key="option.value"
            :value="option.value"
          >
            {{ option.text }}
          </a-select-option>
        </a-select>
        <a-button icon="search" @click="onSearchBtnClick">查询</a-button>
      </div>
      <!-- table -->
      <div class="table-box">
        <a-table
          :columns="tableColumns"
          :data-source="pluginList"
          :row-key="(record) => record.id"
          :loading="loading"
          :pagination="pagination"
          @change="onTableChange"
        >
          <span slot="status" slot-scope="value">
            {{ statusList[value] }}
            <a-spin v-show="value === 2 || value === 3" size="small" />
          </span>
          <span slot="time" slot-scope="item">{{
            item.status === 1 ? item.gmtModify : ''
          }}</span>
          <span slot="operation" slot-scope="item">
            <span v-show="item.status === 0 || item.status === 1">
              <a @click="operatePlugin(item)">{{ actionList[item.status] }}</a>
              |
            </span>
            <a @click="showLog(item.id)">查看日志</a>
            <a-modal
              title="插件安装日志"
              :visible="logModalVisible"
              :width="800"
            >
              <template slot="footer">
                <a-button type="primary" @click="hideLog">确定</a-button>
              </template>
              <pre style="max-height: 500px;">{{ pluginLogContent }}</pre>
            </a-modal>
          </span>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
/* eslint-disable import/no-cycle */
import { queryAllPlugin, install, uninstall, queryStatus } from '@/api/plugin'

@Component({
  components: {},
})
export default class AuditService extends Vue {
  private loading: boolean = false
  private searchPluginName: string = ''
  private searchPluginStatus: string = ''
  private pluginTaskCheckTimer: any = null
  private logModalVisible: boolean = false
  private pluginLogContent: string = '无日志记录'
  private pluginLogId: number = -1

  private tableColumns = [
    {
      title: '插件名称',
      dataIndex: 'name',
      key: 'name',
      width: '20%',
      ellipsis: true,
    },
    {
      title: '版本号',
      dataIndex: 'version',
      key: 'version',
      width: '10%',
      ellipsis: true,
    },
    {
      title: '插件介绍',
      dataIndex: 'description',
      key: 'description',
      width: '30%',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '10%',
      scopedSlots: { customRender: 'status' },
    },
    {
      title: '安装时间',
      key: 'time',
      width: '15%',
      scopedSlots: { customRender: 'time' },
    },
    {
      title: '操作',
      key: 'operation',
      scopedSlots: { customRender: 'operation' },
    },
  ]

  private pagination: any = {}

  // 所有插件列表
  private pluginList: any[] = []
  // 搜索条件中的插件状态清单
  private filterStatusList: any[] = [
    {
      value: '',
      text: '所有状态',
    },
    {
      value: '0',
      text: '未安装',
    },
    {
      value: '1',
      text: '已安装',
    },
    {
      value: '2',
      text: '安装中',
    },
    {
      value: '3',
      text: '卸载中',
    },
  ]

  private statusList = ['未安装', '已安装', '安装中', '卸载中']
  private actionList = ['安装', '卸载', '', '']

  public mounted() {
    this.queryPluginList()
  }

  public activated() {
    this.pluginTaskCheckTimer = setInterval(
      this.loopQueryPluginTaskStatus,
      2000
    )
  }

  private showLog(pluginId: number) {
    this.pluginLogId = pluginId
    this.logModalVisible = true
  }

  private hideLog() {
    this.pluginLogId = -1
    this.logModalVisible = false
  }

  public deactivated() {
    clearInterval(this.pluginTaskCheckTimer)
    this.pluginTaskCheckTimer = null
  }

  // 正在安装或卸载的插件任务列表，用于轮询查看任务的执行状态
  public get pluginTaskIdList() {
    const taskIdList: number[] = []
    this.pluginList.forEach((plugin) => {
      if (plugin.status === 2 || plugin.status === 3) {
        taskIdList.push(plugin.instanceId)
      }
    })
    return taskIdList
  }

  /**
   * 查询 api
   */
  public queryPluginList() {
    this.loading = true
    const parameters = {
      search: this.searchPluginName,
      status: this.searchPluginStatus,
      pageSize: 10,
      curPage: 1,
    }
    queryAllPlugin({
      data: parameters,
    }).then((response: any) => {
      if (response.data.code === 100) {
        const pagination = { ...this.pagination }
        pagination.total = response.data.result.totalElements
        this.pluginList = response.data.result.data
        this.pagination = pagination
      }
      this.loading = false
    })
  }

  private loopQueryPluginTaskStatus() {
    if (this.pluginTaskIdList.length > 0) {
      queryStatus({
        data: {
          id: this.pluginTaskIdList,
        },
      }).then((response) => {
        const updatedTask = response.data.result.find((task: any) => {
          return task.status === 'success' || task.status === 'fail'
        })

        // 日志窗口打开后，获取插件日志记录
        if (this.logModalVisible) {
          response.data.result.forEach((pluginStatus: any) => {
            if (pluginStatus.pluginId === this.pluginLogId) {
              this.pluginLogContent = pluginStatus.logInfo
            }
          })
        }

        if (updatedTask) {
          this.queryPluginList()
        }
      })
    }
  }

  /* 点击查询 */
  public onSearchBtnClick() {
    this.pagination.current = 1
    this.queryPluginList()
  }

  // eslint-disable-next-line
  public onTableChange(pagination: any, filters: any, sorter: any) {
    this.pagination = pagination
    this.queryPluginList()
  }

  public operatePlugin(item: any) {
    const operate = item.status === 0 ? install : uninstall
    const parameters = { id: item.id }
    operate({ data: parameters }).then(() => {
      this.queryPluginList()
    })
  }
}
</script>

<style lang="less" scoped>
.service-page {
  background: #f0f2f5;
  box-sizing: border-box;
  display: block;
  height: 100%;
  padding: 12px 16px;
  width: 100%;

  .content {
    background: #fff;
    box-sizing: border-box;
    display: flex;
    flex-flow: column nowrap;
    height: 100%;
    padding: 18px;
    width: 100%;
  }

  .search-bar-box {
    display: block;
    min-height: 48px;
    padding-bottom: 18px;
    width: 100%;
  }

  .pluginKeyName {
    margin-right: 20px;
    width: 200px;
  }

  .comp-select {
    margin-left: 10px;
    margin-right: 20px;
    width: 190px;
  }
}

.table-box {
  overflow: auto;
}
</style>
